<?php

require_once BASEPATH.'/db.class.php';

class Model{
   public $db;

   public function __construct(){
      $this->db = new Dbstuff();
      $this->db->connect();
   }
   public function getDelAvFileList($limit = 50){
      $sql = sprintf("SELECT * FROM `video` WHERE `status` = 5 LIMIT %d", $limit);
      $list = $this->db->fetch_all($sql);
      return $list;
   }
   public function getAllowTags(){
      $sql = 'SELECT `name` FROM `graballowtags` ';
      $list = $this->db->fetch_all($sql);
      $tags = array();
      foreach($list as $val){
         $tags[] = $val['name'];
      }
      return $tags;
   }
   public function getBaseServer(){
      $sql = 'SELECT * FROM  `serverlist`
       WHERE   isbase = 1';
      $server = $this->db->fetch_first($sql);
      return $server;
   }
   public function getStorageServer(){
      $sql = 'SELECT * FROM `serverlist` WHERE `serverstatus`=1 ORDER BY `weighted` LIMIT 1';
      $server = $this->db->fetch_first($sql);
      return $server;
   }
   public function getStorageServerBySid($serverid = ''){
      if( !$serverid){
         return false;
      }
      $sql = sprintf("SELECT * FROM `serverlist` WHERE `serverid`= '%s' LIMIT 1", mysql_real_escape_string($serverid));
      $server = $this->db->fetch_first($sql);
      return $server;
   }
   public function getStorageServerList($isdelete = null){
      if(!$isdelete)
        $sql = 'SELECT * FROM `serverlist` WHERE `serverstatus`=1 ';
      else 
        $sql = 'SELECT * FROM `serverlist` ';
      
      $server = $this->db->fetch_all($sql);
      return $server;
   }
   public function setStorageServerUse($disk = array()){
      if( !isset($disk['total']) && !isset($disk['use'])){
         return false;
      }
      $sql = sprintf("UPDATE `serverlist` SET `storageused`=%d, `storagetotal`=%d WHERE `id` = %d LIMIT 1", $disk['use'], $disk['total'], $disk['id']);
      $this->db->query($sql);
      return true;
   }
   public function setStorageServerWeight($id = ''){
      if(!$id){
         return false;
      }
      $sql = sprintf('UPDATE `serverlist` SET `weighted`=`weighted`+1 WHERE `id`=%d LIMIT 1',$id);
      $this->db->query($sql);
      return true;
   } 
   public function setAdvanceVideo($avkey = '',$time = ''){
      if(!$avkey || !$time){
         return false;
      }
      $sql = sprintf('UPDATE `video` SET `createtime` = \'%s\' WHERE `avkey` = \'%s\' LIMIT 1',mysql_real_escape_string($time),mysql_real_escape_string($avkey));
      $this->db->query($sql);
      return true;
   } 
   public function setAvStatusByAvkey($avkey = '', $status = 1){
      if( !$avkey){
         return false;
      }
      $sql = sprintf("UPDATE `video` SET `status` = %d WHERE `avkey`='%s' LIMIT 1", $status, 
             mysql_real_escape_string($avkey));
      $this->db->query($sql);
      return true;
   }
   public function processData($row,$onlyedit =null){
      if(!$row['avkey'])
        return false;

      $userlist = array(array('username'=>'zaki727','uid'=>2028852),
array('username'=>'walter727','uid'=> 2028851),
array('username'=>'sagar','uid'=>2028850),
array('username'=>'whatever727','uid'=>2171767),
array('username'=>'superfrank','uid'=>2173642),
array('username'=>'Zane2011','uid'=>2418761),
array('username'=>'Zafir11','uid'=>2418768),
array('username'=>'Dagsoso','uid'=>2418773),
array('username'=>'Darius','uid'=>2418774),
array('username'=>'aarree','uid'=>2418776),
array('username'=>'gabaibi','uid'=>2418777),
array('username'=>'Garini','uid'=>2418779),
array('username'=>'Jalme','uid'=>2418780),
array('username'=>'mainlet','uid'=>2418781),
array('username'=>'Malik12','uid'=>2418782),
array('username'=>'popowen2','uid'=>2418783),
array('username'=>'iphone10','uid'=>2418836),
array('username'=>'Para00','uid'=>2418854),
array('username'=>'ixian','uid'=>2418860),
array('username'=>'Valingogo','uid'=>2418864),
array('username'=>'igodzz','uid'=>2418865),
array('username'=>'Raghnall','uid'=>2418867),
array('username'=>'Radcliff','uid'=>2418868),
array('username'=>'2yashwant','uid'=>2418872),
array('username'=>'yeshudi','uid'=>2418873),
array('username'=>'taksony','uid'=>2418874),
array('username'=>'tancredo','uid'=>2418875),
array('username'=>'Tannon','uid'=>2418876),
array('username'=>'waghome','uid'=>2418877),
array('username'=>'mians','uid'=>2419078),
array('username'=>'tyy67','uid'=>2419079),
array('username'=>'weijie6936','uid'=>2028845),
array('username'=>'jiejie88','uid'=>2028843),
array('username'=>'zhuqunhua','uid'=>2028846),
array('username'=>'huahua88','uid'=>2028847),
array('username'=>'panweijie88','uid'=>2028842),
array('username'=>'holhol','uid'=>2419080),
array('username'=>'lavender06','uid'=>2419082),
array('username'=>'rayray8','uid'=>2419083),
array('username'=>'gordeng','uid'=>2419084));

     $randkey = rand(0,39);
     $user = $userlist[$randkey];
     $row['username'] = $user['username'];
     $row['uid'] = $user['uid'];
     $row['status'] = 1;
     if(isset($row['tags']))
        $tags = $row['tags'];

      $table = 'video';
      if(isset($row['avkeys'])){
         //new avkey
         $_avkey=$row['avkey'];
         $row['avkey']=$row['avkeys'];
      }
      $data = $this->getAvByid($row['avkey'],null,null,1);
      if(isset($row['tags']))
        unset($row['tags']);

      if(isset($row['avkeys'])){
        //將要修改的avkey賦給avkey
        $row['avkey']=$_avkey;
        unset($row['avkeys']);
      }
      if($data['avkey'])
          $sql = $this->db->update_string($table,$row,array('vid'=> $data['vid']));
      else{
          $sql = $this->db->insert_string($table,$row);
      }
      $query = $this->db->query($sql);
      $vid = (isset($data['vid']) && $data['vid']>0) ? $data['vid'] : $this->db->insert_id();

      if($onlyedit)
         return true;

      $sql = sprintf("DELETE FROM videotag WHERE vid = '%d'" ,$vid);
      $query = $this->db->query($sql);

      $tags = explode(",",$tags);
      foreach($tags as $k => $v){
          $sql = sprintf(" SELECT tagid FROM  `tag` WHERE  `name` = '%s' LIMIT 1",mysql_real_escape_string($v));
          $query = $this->db->query($sql);
          if($this->db->num_rows($query) < 1){
              $sql = $this->db->insert_string('tag',array('name'=>trim($v),'status'=>1));
              $query = $this->db->query($sql);
              $tagid = $this->db->insert_id();
          }else{
              $tagdata = $this->db->fetch_array($query);
              $tagid = $tagdata['tagid'];
              //更新tag去掉空格
              if($v != $tagdata['name']){
                 $sql = sprintf("UPDATE `tag` SET `name`='%s' WHERE `tagid`=%d LIMIT 1", mysql_real_escape_string(trim($v)), $tagid);
                 $this->db->query($sql);
              }
          }

          $sql = $this->db->insert_string('videotag',array('tagid'=>$tagid,'vid'=>$vid));
          $query = $this->db->query($sql);
          $sql = sprintf("UPDATE tag SET videocount = (SELECT COUNT( v.vid ) FROM video AS v LEFT JOIN  `videotag` vt ON v.vid = vt.vid WHERE v.createtime <='%s' AND v.status =1 AND `tagid` = %d) WHERE tagid = %d",date('Y-m-d'),$tagid,$tagid);
          $query = $this->db->query($sql);
      }
      $data = $this->getAvByid($row['avkey'],null,null,1);
//update av relatedata
       $taglists = $this->getTagsByVid($data['vid']);
       $lists = $this->getRelatedVideo($taglists,9,$data['vid']);
       if($lists){
          $lists=serialize($lists);
          $sql=sprintf('UPDATE `video` SET `relatedata`=\'%s\',`flag`=1 WHERE `vid`=%d LIMIT 1',mysql_real_escape_string($lists),$data['vid']);
          $this->db->query($sql);
       }
       return $data;
    }

    public function getAvByid($avkey = null,$isb = null,$isdownload = null,$isadmin = null){
      if(!$avkey)
        return false;

      $moresql = ' AND status = 1 ';
      if($isadmin)
          $moresql = '  ';

      $avK = str_replace('-','',$avkey);
      if($avK == $avkey){
         $avK = sprintf('avkey = \'%s\' ',mysql_real_escape_string($avkey));
      }else{
         $avK = sprintf('(avkey = \'%s\' or avkey = \'%s\')',mysql_real_escape_string($avkey),mysql_real_escape_string($avK));
      }
      $sql = sprintf("SELECT * FROM `video` WHERE %s %s LIMIT 1",$avK,$moresql);
      $query = $this->db->query($sql);
      if($this->db->num_rows($query) < 1)
            return false;

      $filenameExtension = ".flv";
      if($isdownload)
        $filenameExtension = ".avi";

      $row = $this->db->fetch_array($query);
      if($row['ismp4']==1)
        $filenameExtension = ".mp4";

      if($isb&&$row['bkey'])
        $row['videourl'] = $this->getVideoUrl($row['bkey'].$filenameExtension,$row['serverid']);
      else
        $row['videourl'] = $this->getVideoUrl($row['avkey'].$filenameExtension,$row['serverid']);

      return $row;
   }
   public function getVideoUrl($videoname,$serverid,$isvip=null){
          $f      ="/".$videoname;
          $vip    = "";
          $p      = '';
          if($serverid === '136-170-2' || $serverid==='136-170')
            $p = ':8888';

          $secret = "iloveallen";
          if($isvip){
              $vip = "vip";
              $secret = "goldallen";
          }
          $http   = sprintf("http://1.fs%s.%sav.ckcdn.com%s",$serverid,$vip,$p);
          $uri_prefix = "/dl/";
          $t      = time();
          $t_hex  = sprintf("%08x", $t);
          $m      = md5($secret.$f.$t_hex);
          $videopath = sprintf('%s%s%s/%s%s',$http,$uri_prefix, $m, $t_hex, $f);
          return $videopath;
  }
   public function getRelatedVideo($tags = null,$count = 10,$vid=''){
      if(!$tags)
          return ;

      $ids = array();
      foreach($tags as $k => $v){
          $ids[] = $v['tagid'];
      }
      $where = $vid ? ' AND `video`.`vid`!='.intval($vid) : '';
      $idstring = implode(",",$ids);
      $sql = sprintf("SELECT `video`.`isessence`,`video`.`username`, `video`.`avkey`, `video`.`title`,`video`.`serverid` FROM `video` LEFT JOIN `videotag` as vt ON `video`.`vid` = vt.vid  WHERE vt.`tagid` IN (%s)  ",$idstring);
      $sql.= $where.' AND `video`.`createtime` <= \''.date("Y-m-d"). '\' AND `video`.`status` = 1 LIMIT '.intval($count) ;

      $lists = $this->db->fetch_all($sql);
      if(!$lists)
          return false;

      foreach($lists as $k => $v){
          $lists[$k]['picurl'] = $this->getPicUrl($v['avkey'],$v['serverid'],'b');
      }

      return $lists;
   }
   function getTagsByVid($vid = null){
      if(!$vid)
        return;

      $sql = sprintf("SELECT t.tagid , t.name FROM tag AS t , videotag vt WHERE vt.vid = %d AND vt.tagid = t.tagid ",$vid);

      $lists = $this->db->fetch_all($sql);
      if(count($lists) < 1)
            return false;

      return $lists;
  }
  public function getPicUrl($avkey = null,$serverid = 1 ,$pictype = 's'){
      $p = '';
      if($serverid === '136-170' || $serverid === '136-170-2')
        $p = ':8888';

      $imgPatt      = "http://%s.fs%s.av.ckcdn.com%s/%s-%s.jpg";
      $e = isset($avkey[4])?strtolower($avkey[4]):9;
      switch($e){
        default:
          $pre = 0;
        break;
        case '0':
        case '1':
        case '2':
        case '7':
          $pre = 0;
        break;
        case '3':
        case '4':
        case 'a':
        case 'b':
        case 'c':
        case 'd':
        case 'e':
        case 'f':
          $pre = 1;
        break;
        case '5':
        case '6':
        case 'g':
        case 'h':
        case 'i':
        case 'j':
        case 'k':
        case 'l':
        case 'm':
          $pre = 2;
        break;
        case '8':
        case '9':
        case 'n':
        case 'o':
        case 'p':
        case 'q':
        case 'r':
          $pre = 3;
        break;
        case 's':
        case 't':
        case 'u':
        case 'v':
        case 'w':
        case 'x':
        case 'y':
        case 'z':
          $pre = 4;
        break;
      }
      return sprintf($imgPatt,$pre,$serverid,$p,$avkey,$pictype);
  }
}
